package io.litchi.auth.Infrastructure.exception;

import io.litchi.auth.Infrastructure.exception.type.RefreshTokenExpiredException;
import io.litchi.common.exception.LitchiException;
import io.litchi.common.result.Result;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * description: 统一异常处理
 *
 * @author helang
 * @since 2025-09-12
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class LitchiExceptionHandler {

    private static final String SYS_EXCEPTION_MESSAGE = "系统走丢了,请稍候再试";

    /**
     * 系统异常
     *
     * @param e e
     * @return Result<Void>
     */
    @ExceptionHandler(Exception.class)
    public Result<Void> handlerException(Exception e) {
        log.error("系统异常:{}", e.getMessage());
        return Result.fail(SYS_EXCEPTION_MESSAGE);
    }

    /**
     * 通用业务异常
     *
     * @param e e
     * @return Result<Void>
     */
    @ExceptionHandler(LitchiException.class)
    public Result<Void> handlerLitchiException(LitchiException e) {
        log.error("通用业务异常:{}", e.getMessage());
        return Result.fail(e.getMessage());
    }

    /**
     * refreshToken异常
     *
     * @param e e
     * @return Result<Void>
     */
    @ExceptionHandler(RefreshTokenExpiredException.class)
    public Result<Void> handlerRefreshTokenExpiredException(RefreshTokenExpiredException e) {
        log.error("refreshToken异常:{}", e.getMessage());
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class, ConstraintViolationException.class})
    public Result<Void> handlerMethodArgumentNotValidException(Exception e) {
        String errorMessage = "参数异常:";
        if (e instanceof MethodArgumentNotValidException) {
            errorMessage = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
        } else if (e instanceof ConstraintViolationException) {
            errorMessage = ((ConstraintViolationException) e).getConstraintViolations().iterator().next().getMessage();
        }
        return Result.fail(errorMessage);
    }
}